import {defineStore} from 'pinia'
import {ref} from 'vue'
import {sleep, treeToArray} from '@/utils'
import router from '@/router'
import homeList from '@/router/modules/home.js'
import _ from 'lodash'
import {useRouter} from 'vue-router'


export default defineStore('menuStore', () => {
  const menuList = ref([])
  const dynamicMenuList = ref([])
  const tagList = ref([])


  function initMenu() {
    return new Promise(async (resolve, reject) => {
      // 获取动态路由
      await sleep()
      dynamicMenuList.value = [{
        path: '/',
        component: () => import('@/layout/index.vue'),
        children: [
          {
            path: '/dynamic',
            name: 'dynamic',
            meta: {
              label: '动态路由',
              icon: 'Ticket'
            },
            component: () => import('@/views/dynamic/index.vue')
          }
        ]
      }]
      dynamicMenuList.value.forEach(menu => {
        router.addRoute(menu)
        // if (!menuList.value.some(item => item.path === menu.path)) {
        //   menuList.value.push(menu)
        // }
        // menuList.value.push(menu)
        // console.log(menuList.value, 'menuList.value')
      })
      menuList.value = [...homeList, ...dynamicMenuList.value]

      // 动态添加路由
      if (!router.hasRoute('404')) {
        router.addRoute({
          path: '/:pathMatch(.*)*',
          name: '404',
          component: () => import('@/views/error/404.vue')
        })
      }

      resolve(router)
    })
  }

  function addTag(data) {
    const result = ref(treeToArray(_.cloneDeep(menuList.value))?.filter(item => item?.meta && item.path !== '/'))
    const isMenuFind = result.value.find(item => item.name === data.name)
    const isTagFind = tagList.value.find(item => item.name === data.name)
    // 标签不存在，菜单存在
    if (!isTagFind && isMenuFind) tagList.value.push(data)
  }

  const router = useRouter()

  function removeTag(name) {
    const findIndex = tagList.value.findIndex(item => item.name === name);

    if (findIndex === -1) return; // 如果没有找到，直接返回

    // 删除对应的标签
    tagList.value.splice(findIndex, 1);

    // 计算下一个索引
    const nextIndex = findIndex > 0 ? findIndex - 1 : 0;
    const nextItem = tagList.value[nextIndex];

    // 跳转到下一个标签
    if (nextItem) {
      router.push({name: nextItem.name});
    }

  }

  return {menuList, initMenu, dynamicMenuList, tagList, addTag, removeTag}
})